const DietMeal = require('../models/DietMeal');

// 获取用户特定日期的餐食
exports.getMealsByDate = async (req, res) => {
  try {
    const { date } = req.query;
    const userId = req.user._id;
    
    if (!date) {
      return res.status(400).json({
        success: false,
        message: '需要提供日期参数'
      });
    }
    
    // 处理日期查询
    const startDate = new Date(date);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(date);
    endDate.setHours(23, 59, 59, 999);
    
    const meals = await DietMeal.find({
      userId,
      date: { $gte: startDate, $lte: endDate }
    }).sort({ time: 1 });
    
    res.status(200).json({
      success: true,
      count: meals.length,
      data: meals
    });
  } catch (error) {
    console.error('获取餐食失败:', error);
    res.status(500).json({
      success: false,
      message: '获取餐食失败',
      error: error.message
    });
  }
};

// 获取单个餐食详情
exports.getMealById = async (req, res) => {
  try {
    const meal = await DietMeal.findById(req.params.id);
    
    if (!meal) {
      return res.status(404).json({
        success: false,
        message: '未找到该餐食记录'
      });
    }
    
    // 检查该餐食是否属于当前用户
    if (meal.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权访问此餐食记录'
      });
    }
    
    res.status(200).json({
      success: true,
      data: meal
    });
  } catch (error) {
    console.error('获取餐食详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取餐食详情失败',
      error: error.message
    });
  }
};

// 添加新餐食
exports.addMeal = async (req, res) => {
  try {
    const { mealType, date, time, foods, note, tags } = req.body;
    const userId = req.user._id;
    
    // 验证必需字段
    if (!mealType || !date || !time || !foods || !Array.isArray(foods) || foods.length === 0) {
      return res.status(400).json({
        success: false,
        message: '缺少必需字段或食物列表为空'
      });
    }
    
    // 计算总营养值
    const totalNutrition = foods.reduce((totals, food) => {
      totals.totalCalories += parseFloat(food.calories) || 0;
      totals.totalCarbs += parseFloat(food.carbs) || 0;
      totals.totalProtein += parseFloat(food.protein) || 0;
      totals.totalFat += parseFloat(food.fat) || 0;
      return totals;
    }, { totalCalories: 0, totalCarbs: 0, totalProtein: 0, totalFat: 0 });
    
    // 创建新餐食记录
    const meal = new DietMeal({
      userId,
      mealType,
      date: new Date(date),
      time,
      foods,
      note,
      tags,
      ...totalNutrition // 添加计算好的总营养值
    });
    
    await meal.save();
    
    res.status(201).json({
      success: true,
      message: '成功添加餐食记录',
      data: meal
    });
  } catch (error) {
    console.error('添加餐食失败:', error);
    res.status(500).json({
      success: false,
      message: '添加餐食失败',
      error: error.message
    });
  }
};

// 更新餐食记录
exports.updateMeal = async (req, res) => {
  try {
    const { mealType, date, time, foods, note, tags } = req.body;
    
    // 检查餐食是否存在
    let meal = await DietMeal.findById(req.params.id);
    
    if (!meal) {
      return res.status(404).json({
        success: false,
        message: '未找到该餐食记录'
      });
    }
    
    // 检查该餐食是否属于当前用户
    if (meal.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权修改此餐食记录'
      });
    }
    
    // 更新餐食信息
    if (mealType) meal.mealType = mealType;
    if (date) meal.date = new Date(date);
    if (time) meal.time = time;
    if (foods && Array.isArray(foods) && foods.length > 0) meal.foods = foods;
    if (note !== undefined) meal.note = note;
    if (tags) meal.tags = tags;
    
    await meal.save();
    
    res.status(200).json({
      success: true,
      message: '成功更新餐食记录',
      data: meal
    });
  } catch (error) {
    console.error('更新餐食失败:', error);
    res.status(500).json({
      success: false,
      message: '更新餐食失败',
      error: error.message
    });
  }
};

// 删除餐食记录
exports.deleteMeal = async (req, res) => {
  try {
    // 检查餐食是否存在
    const meal = await DietMeal.findById(req.params.id);
    
    if (!meal) {
      return res.status(404).json({
        success: false,
        message: '未找到该餐食记录'
      });
    }
    
    // 检查该餐食是否属于当前用户
    if (meal.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({
        success: false,
        message: '无权删除此餐食记录'
      });
    }
    
    await meal.deleteOne();
    
    res.status(200).json({
      success: true,
      message: '餐食记录已删除'
    });
  } catch (error) {
    console.error('删除餐食失败:', error);
    res.status(500).json({
      success: false,
      message: '删除餐食失败',
      error: error.message
    });
  }
};

// 获取用户营养摄入统计
exports.getNutritionStats = async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    const userId = req.user._id;
    
    // 默认获取最近7天的数据
    const end = endDate ? new Date(endDate) : new Date();
    end.setHours(23, 59, 59, 999);
    
    const start = startDate ? new Date(startDate) : new Date(end);
    start.setDate(start.getDate() - 6);
    start.setHours(0, 0, 0, 0);
    
    // 查询该日期范围内的所有餐食
    const meals = await DietMeal.find({
      userId,
      date: { $gte: start, $lte: end }
    });
    
    // 按日期分组统计
    const dailyStats = {};
    const dateFormatter = new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
    
    meals.forEach(meal => {
      const dateStr = dateFormatter.format(meal.date);
      
      if (!dailyStats[dateStr]) {
        dailyStats[dateStr] = {
          calories: 0,
          carbs: 0,
          protein: 0,
          fat: 0,
          meals: []
        };
      }
      
      dailyStats[dateStr].calories += meal.totalCalories;
      dailyStats[dateStr].carbs += meal.totalCarbs;
      dailyStats[dateStr].protein += meal.totalProtein;
      dailyStats[dateStr].fat += meal.totalFat;
      dailyStats[dateStr].meals.push({
        id: meal._id,
        mealType: meal.mealType,
        time: meal.time,
        calories: meal.totalCalories
      });
    });
    
    // 计算整个时期的平均值
    let totalDays = Object.keys(dailyStats).length;
    let averageStats = {
      calories: 0,
      carbs: 0,
      protein: 0,
      fat: 0
    };
    
    if (totalDays > 0) {
      let totalCalories = 0, totalCarbs = 0, totalProtein = 0, totalFat = 0;
      
      Object.values(dailyStats).forEach(day => {
        totalCalories += day.calories;
        totalCarbs += day.carbs;
        totalProtein += day.protein;
        totalFat += day.fat;
      });
      
      averageStats.calories = Math.round(totalCalories / totalDays);
      averageStats.carbs = Math.round(totalCarbs / totalDays * 10) / 10;
      averageStats.protein = Math.round(totalProtein / totalDays * 10) / 10;
      averageStats.fat = Math.round(totalFat / totalDays * 10) / 10;
    }
    
    res.status(200).json({
      success: true,
      data: {
        dailyStats,
        averageStats,
        period: {
          start: start.toISOString().split('T')[0],
          end: end.toISOString().split('T')[0],
          days: totalDays
        }
      }
    });
  } catch (error) {
    console.error('获取营养统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取营养统计失败',
      error: error.message
    });
  }
}; 